package org.viva.api;

import java.io.StringWriter;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.viva.core.exception.SystemException;
import org.viva.core.util.UTIL;

/**
 * velocity模版工具
 * <table border=1> <tr> <td>RESOURCE_LOADER</td> <td>class</td> </tr> <tr>
 * <td>runtime.log</td> <td>null</td> </tr> </tr> <tr>
 * <td>class.resource.loader.class</td> <td>ClasspathResourceLoader</td> </tr>
 * <tr> <td>OUTPUT_ENCODING</td> <td>UTF-8</td> </tr> <tr>
 * <td>INPUT_ENCODING</td> <td>UTF-8</td> </tr> <tr>
 * <td>modificationCheckInterva</td> <td>2</td> </tr> </table>
 * 
 * @author <a href="mailto:lichaohn@163.com">lichao</a>
 */
public class VM {

    private static VelocityEngine ve;

    static {
        init1();
    }

    private static void init1() {
        ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("runtime.log", "");
        ve.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
        ve.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
        ve.setProperty("file.resource.loader.cache", false);
        ve.setProperty("file.resource.loader.modificationCheckInterva", "2");
        ve.init();
    }

    public static String vm(String path, VelocityContext context) {
        StringWriter writer = new StringWriter();
        try {
            context = context == null ? new VelocityContext() : context;
            path = path.startsWith("/") ? path : "/" + path;
            context.put("FORMAT", UTIL.FORMAT);
            ve.mergeTemplate(path, "UTF-8", context, writer);
        } catch (Exception e) {
            throw new SystemException(e);
        }
        return writer.toString();
    }

    public static String strTemp(String vmString, VelocityContext context) {
        StringWriter writer = new StringWriter();
        ve.evaluate(context, writer, "", vmString);
        return writer.toString();
    }

}
